package com.freedom.rpc.thrift.client;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TFramedTransport;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;

import com.freedom.rpc.thrift.client.socket.MyTSocket;
import com.freedom.rpc.thrift.client.socket.TSocketPool;
import com.freedom.rpc.thrift.client.utils.MyClientProperties;
import com.freedom.rpc.thrift.common.service.HelloWorldService;
import com.freedom.rpc.thrift.common.utils.LoggerUtils;

public class MyClient {
	//
	private static final Logger logger = LogManager.getLogger(MyClient.class);

	public static void main(String[] args) {
		for (int i = 0; i < 1; i++) {
			test();
		}
	}

	public static void test() {

		MyTSocket socket = null;
		try {
			socket = TSocketPool.getInstance().borrowObject();
			if (null == socket) {
				throw new Exception("fail to fetch a socket from pool...");
			}
			TTransport transport = new TFramedTransport(socket);
			TProtocol protocol = new TBinaryProtocol(transport);
			TMultiplexedProtocol tMultiProtocol = new TMultiplexedProtocol(protocol, "HelloWorldService");
			HelloWorldService.Client client = new HelloWorldService.Client(tMultiProtocol);
			//
			// 接下来，可以调用你自己在.thrift文件里定义的方法
			// [由于thrift把一些内部方法也定义为public
			// 所以调用时注意只调用自己定义的接口方法，其它不要调用，以免出错]
			long start = System.currentTimeMillis();
			System.out.println("client.helloBoolean(false)---" + client.helloWorldBoolean(3));
			LoggerUtils.debug(logger, "耗时：" + (System.currentTimeMillis() - start) + " ms");
			//
			start = System.currentTimeMillis();
			System.out.println("client.helloString(\"360buy\")---" + client.helloWorldString("360buy"));
			LoggerUtils.debug(logger, "耗时：" + (System.currentTimeMillis() - start) + " ms");
			//
			start = System.currentTimeMillis();
			System.out.println("client.helloString(\"360buy\")---" + client.helloWorldString("360buy"));
			LoggerUtils.debug(logger, "耗时：" + (System.currentTimeMillis() - start) + " ms");
			//
			start = System.currentTimeMillis();
			System.out.println("client.helloBoolean(false)---" + client.helloWorldBoolean(3));
			LoggerUtils.debug(logger, "耗时：" + (System.currentTimeMillis() - start) + " ms");
			//
		} catch (Exception e) {
			LoggerUtils.error(logger, e.toString());
			if (null != socket) {// 通过业务侧，我们也做了连接可用性的探测
				socket.setAlive(false);
			}
		} finally {
			if (null != socket) {// 可以的话，需要返回给连接池
				TSocketPool.getInstance().returnObject(socket);
			}
		}
	}
}
